package com.formation.userbase.persistance.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;

import com.formation.userbase.persistance.beans.Product;

@Service(value = "productdaobean")
public class ProductHibernateDao implements ProductDao {

	@Resource(name="mysessionfactory")
	SessionFactory sessF;

	public ProductHibernateDao() {
		// TODO Auto-generated constructor stub
	}

	public SessionFactory getSessF() {
		return sessF;
	}

	public void setSessF(SessionFactory sessF) {
		this.sessF = sessF;
	}

	@Override
	public Product findProductByRef(String ref) {
		
		Session session = sessF.openSession();
		try {
			// session.beginTransaction();
			// Query q =
			// session.createSQLQuery("Select EVENT_ID, EVENT_DATE, title from events e where e.EVENT_ID =:eventId");

			Query q = session
					.createQuery("from Product as p where u.reference =:maReference");
			q.setString("maReference", ref);

			return (Product) q.uniqueResult();
		} catch (RuntimeException e) {
			// if(tx != null) tx.rollback();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public List<Product> getAllProduct() {
		Session session = sessF.openSession();;
		try {
			// session.beginTransaction();
			// Query q =
			// session.createSQLQuery("Select EVENT_ID, EVENT_DATE, title from events e where e.EVENT_ID =:eventId");

			Query q = session.createQuery("from Product as p ");

			return (List<Product>) q.list();
		} catch (RuntimeException e) {
			// if(tx != null) tx.rollback();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public boolean insert(Product p) {
		Session session = sessF.openSession();;
		Transaction tx = null;
		try {
			// System.out.println("heeee"+u.getLogin());
			tx = session.beginTransaction();
			session.save(p);
			tx.commit();
			return true;
		} catch (RuntimeException e) {
			// if(tx != null) tx.rollback();
			e.printStackTrace();
			return false;
		} finally {
			session.close();
		}
	}

}
